package org.zjsru.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.zjsru.pojo.Product;
import org.zjsru.pojo.User;
import org.zjsru.service.ProductService;
import org.zjsru.service.DefaultProductService;
import org.zjsru.feign.UserClient;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/product") // 类级别路径
public class ProductController {
    
    @Value("${server.port}")
    private String serverPort;
    
    @Autowired
    private ProductService productService;

    @Autowired
    private UserClient userClient;

    @Autowired
    private DefaultProductService defaultProductService;

    /**
     * 获取产品详情
     * @param productId 产品ID
     * @param userId 用户ID（从网关传递）
     * @return 产品信息
     */
    @GetMapping("/detail/{productId}")
    public Product getProductDetail(
            @PathVariable("productId") Long productId,
            @RequestHeader("X-User-Id") Long userId) {
        log.info("产品服务[端口:{}]接收到查询产品详情请求：productId={}, userId={}", serverPort, productId, userId);
        
        // 获取商品信息
        Product product = productService.getProductById(productId);
        
        // 验证用户状态
        try {
            User user = userClient.checkUserStatus(userId);
            if (user != null) {
                log.info("产品服务[端口:{}]用户状态验证通过：{}", serverPort, user.getUsername());
                return product;
            }
        } catch (Exception e) {
            log.error("产品服务[端口:{}]用户状态验证失败：{}", serverPort, e.getMessage());
        }
        
        log.info("产品服务[端口:{}]用户服务降级，返回默认商品", serverPort);
        return defaultProductService.getDefaultProduct();
    }

    // 添加库存扣减接口
    @PostMapping("/deduct")
    public String deductStock(
            @RequestParam Long productId,
            @RequestParam int count
    ) {
        log.info("接收到库存扣减请求：productId={}, count={}", productId, count);
        try {
            productService.deductStock(productId, count);
            return "库存扣减成功";
        } catch (RuntimeException e) {
            log.error("库存扣减失败：{}", e.getMessage());
            return "库存扣减失败：" + e.getMessage();
        }
    }

    // 添加恢复库存接口
    @PostMapping("/restore-stock")
    public String restoreStock(
            @RequestParam Long productId,
            @RequestParam int count
    ) {
        log.info("接收到恢复库存请求：productId={}, count={}", productId, count);
        try {
            // 调用负数扣减来恢复库存
            productService.deductStock(productId, -count);
            return "库存恢复成功";
        } catch (RuntimeException e) {
            log.error("库存恢复失败：{}", e.getMessage());
            return "库存恢复失败：" + e.getMessage();
        }
    }
}
